package cn.sumpu.app.guoguojie.util;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import cn.sumpu.app.guoguojie.constant.DoingProductFrom;
import cn.sumpu.app.guoguojie.constant.DoingProductStatus;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.response.ItemGetResponse;


public class DoingProductUtil {
	
	/**
	 * 得到淘宝的商品信息
	 * 
	 * @param url
	 * @throws Exception
	 */
	public static ProductBs getTaobaoPro(String url) throws Exception {
		
		ProductBs pro = new ProductBs();
		
		Document doc = getURLContent(url);
		Elements title = doc.getElementsByClass("tb-detail-hd");
		for (Element element : title) {
			pro.setName(element.getElementsByTag("h3").text());
		}
		if(Common.empty(pro.getName())){
			Elements title2 = doc.getElementsByClass("detail-hd");
			for (Element element : title2) {
				pro.setName(element.getElementsByTag("h3").text());
			}
		}
		Element price = doc.getElementById("J_StrPrice");
		String priceStr = price.text();
		
		pro.setPrice(Double.parseDouble(priceStr.split("-")[0]));

		Element pic = doc.getElementById("J_ImgBooth");
		String picUrl = pic.attr("src");
		if(!Common.empty(picUrl)){
			picUrl = picUrl.substring(0, picUrl.length()-12);
		}
		pro.setPicUrl(picUrl);
		pro.setLinkUrl(urlParseTaobao(url));
		pro.setFrom("淘宝");
		return pro;
	}
	
	/**
	 * 通过淘宝的api得到淘宝的商品信息
	 * 
	 * @param url
	 * @throws Exception
	 */
	public static ProductBs getTaobaoPro(String url,String xtaoAppkey,String xtaoAppsecret,String xtaoPid,String xtaoUrl) throws Exception {
		
		ProductBs pro = new ProductBs();
		String id = Common.getParaValue(url,"id");
		
		TaobaoClient client = new DefaultTaobaoClient(xtaoUrl, xtaoAppkey, xtaoAppsecret); 
		ItemGetRequest req=new ItemGetRequest();
		req.setFields("nick,title,price,pic_url,item_img,approve_status,item_imgs");
		req.setNumIid(Long.parseLong(id));
		ItemGetResponse response = client.execute(req,null);
		Item item = response.getItem();
		pro.setSellerNick(item.getNick());
		pro.setName(item.getTitle());
		pro.setPrice(Double.parseDouble(item.getPrice()));
		pro.setPicUrl(item.getPicUrl());
		pro.setLinkUrl(urlParseTaobao(url));
		pro.setFrom(DoingProductFrom.TAOBAO.getValue());
		pro.setOriginalId(id);
		pro.setMaxPrice(Double.parseDouble(item.getPrice()));
		pro.setImgs(item.getItemImgs());
		//设置商品状态
		if("onsale".equals(item.getApproveStatus())){
		    pro.setStatus(DoingProductStatus.ONSALE.getValue());
		}else{
		    pro.setStatus(DoingProductStatus.NOSALE.getValue());
		}
		return pro;
	}

	/**
	 * 得到京东的商品信息
	 * 
	 * @param url
	 * @throws Exception
	 */
	public static ProductBs get360buyPro(String url) throws Exception {
		ProductBs pro = new ProductBs();
		Document doc = getURLContent(url);
		Element title = doc.getElementById("name");
		pro.setName(title.getElementsByTag("h1").text());
//		商品价格利用京东的微博分享的script。  var content = "我在@京东商城 发现了一个非常不错的商品：苏泊尔32cm真不锈健康铁炒锅FC32T4，京东价：￥209.00。感觉不错，分享一下";
	//	String content = doc.html();
	//	content = content.substring(content.indexOf("京东价：￥")+5);
	//	String price = content.substring(0, content.indexOf("。感觉不错，分享一下")); 
		
		Element pic = doc.getElementById("spec-n1");
		pro.setPicUrl(pic.getElementsByTag("img").attr("src"));
	//	pro.setPrice(Double.parseDouble(price));
		pro.setLinkUrl(url);
		pro.setFrom("京东");
		return pro;

	}

	/**
	 * 得到拍拍的信息
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static ProductBs getPaipaiPro(String url) throws Exception {
		
		String lastUrl = url.substring(url.lastIndexOf("/")+1);
		
		String ppId = "";
		if(lastUrl.lastIndexOf(".html")!=-1){
			ppId = lastUrl.substring(0,lastUrl.lastIndexOf(".html"));
			ppId = ppId.split("-")[0];
		}else{
		/*  问号的转义字符\\u003F点的转义：. ==> u002E 
			美元符号的转义：$ ==> u0024 
			乘方符号的转义：^ ==> u005E 
			左大括号的转义：{ ==> u007B 
			左方括号的转义：[ ==> u005B 
			左圆括号的转义：( ==> u0028 
			竖线的转义：| ==> u007C 
			右圆括号的转义：) ==> u0029 
			星号的转义：* ==> u002A 
			加号的转义：+ ==> u002B 
			问号的转义：? ==> u003F 
			反斜杠的转义： ==> u005C */
			ppId = lastUrl.split("\\u003F")[0];
		}
//		腾讯拍拍的api的地址，返回json格式对象
		String realuUrl = "http://api.paipai.com/item/getItem.xhtml?format=xml&itemCode="+ppId;
		
		ProductBs pro = new ProductBs();
		URL urlObj = new URL(realuUrl);
		URLConnection connection = urlObj.openConnection();
		InputStream is = connection.getInputStream();
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		org.w3c.dom.Document doc = builder.parse(is);
		
		NodeList nodeList = doc.getElementsByTagName("errorCode");
		Node errorCode = nodeList.item(0);
		String errorCodeValue = errorCode.getFirstChild().getNodeValue();
//		如果为0则表示返回成功，否则失败
		if(errorCodeValue.equals("0")){
			Node itemName = doc.getElementsByTagName("itemName").item(0);
			Node itemPrice = doc.getElementsByTagName("itemPrice").item(0);
			Node picLink = doc.getElementsByTagName("picLink").item(0);
			pro.setName(itemName.getFirstChild().getNodeValue());
			pro.setPrice(Double.parseDouble(itemPrice.getFirstChild().getNodeValue())/100);
			pro.setPicUrl(picLink.getFirstChild().getNodeValue());
		}
		
		pro.setLinkUrl(url);
		pro.setFrom("拍拍");
		return pro;
	}
	
	/**
	 * 得到当当的信息
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static ProductBs getDangDangPro(String url) throws Exception {
		
		ProductBs pro = new ProductBs();
		Document doc = getURLContent(url);
		Elements prices  = doc.getElementsByClass("price_d");
		double price = 0;
		for (Element element : prices) {
			Elements numElements = element.getElementsByClass("num");
			for (Element num : numElements) {
				String p = num.text();
				if(!Common.empty(p)){
					price = Double.parseDouble(p.substring(1));
				}
			}
		}
		pro.setPrice(price);
		
		String name = null;
		Elements names = doc.getElementsByClass("h1_title");
		for (Element element : names) {
			Elements namesText = element.getElementsByTag("h1");
			for (Element element2 : namesText) {
				name = element2.text();
			}
		}
		
		Element picEle = doc.getElementById("largePic");
		String picUrl = picEle.attr("src");
		pro.setPicUrl(picUrl);
		pro.setName(name);
		pro.setLinkUrl(url);
		pro.setFrom("当当");
		return pro;
	} 
	
	/**
	 * 得到凡客的信息
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static ProductBs getVanclPro(String url) throws Exception {
		
		ProductBs pro = new ProductBs();
		Document doc = getURLContent(url);
		Element  nameEle  = doc.getElementById("productname");
		String name = nameEle.text();
		
		double price = 0;
		Elements priceEls = doc.getElementsByClass("cuxiaoPrice");
		for (Element element : priceEls) {
			Elements spans = element.getElementsByTag("span");
			for (Element span : spans) {
				Elements strongs = span.getElementsByTag("strong");
				for (Element strong : strongs) {
					price = Double.parseDouble(strong.text());
				}
			}
		}

		String picUrl =doc.getElementById("midimg").attr("src");
		
		
		pro.setPicUrl(picUrl);
		pro.setName(name);
		pro.setPrice(price);
		pro.setLinkUrl(url);
		pro.setFrom("凡客");
		return pro;
	}
	
	/**
	 * 得到产品信息
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static ProductBs getProductInfo(String url,String xtaoAppkey,String xtaoAppsecret,String xtaoPid,String xtaoUrl)throws Exception{
		if(Common.empty(url)) return null;
		ProductBs pb = null;
		if(url.indexOf("item.taobao.com") != -1 || url.indexOf("tmall.com") != -1 || url.indexOf("ershou.taobao.com") != -1){
			pb = getTaobaoPro(url,xtaoAppkey,xtaoAppsecret,xtaoPid,xtaoUrl);
		}else if(url.indexOf("360buy.com") != -1){
			pb = get360buyPro(url);
		}else if(url.indexOf("auction1.paipai.com") != -1 || url.indexOf("auction2.paipai.com") != -1){
			pb = getPaipaiPro(url);
		}else if(url.indexOf("product.dangdang.com") != -1){
			pb = getDangDangPro(url);
		}else if(url.indexOf("item.vancl.com") != -1){
			pb = getVanclPro(url);
		}
		//设置原始ID
		if(pb != null && Common.emptyStr(pb.getOriginalId())){
		    pb.setOriginalId(Common.getParaValue(url,"id"));
		}
		return pb;
	}

	/**
	 * 获取网页的内容
	 */
	private static Document getURLContent(String url) throws Exception {
		Document doc = Jsoup.connect(url).data("query", "Java").userAgent(
				"Mozilla").cookie("auth", "token").timeout(6000).get();
		return doc;
	}
//	只取淘宝的ID
	public static String urlParseTaobao(String url) throws Exception{
		 URL aURL = new URL(url); 
		 
		 
        String protocol = aURL.getProtocol();
        String host = aURL.getHost();
        String query = aURL.getQuery();
        String path = aURL.getPath();
        if(query!=null && !query.equals("")){
       	 String[] paras = query.split("&");
       	 for (String para : paras) {
       		 String[] kv = para.split("=");
       		 if(kv[0] != null && kv[0].equals("id")){
       			 url = protocol+"://"+host+path+"?"+para;
       		 }
			}
        }
		return url;
	}
}
